package com.supermap.gwfs.datashare.of.service;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.supermap.gwfs.datashare.entity.GridForecast;
import com.supermap.gwfs.datashare.entity.Server;
import com.supermap.gwfs.datashare.service.ServerService;
import com.supermap.gwfs.datashare.util.FTPClientFactory;
import com.supermap.gwfs.datashare.util.Logger;
import org.springframework.stereotype.Service;

/**  
 * @Description: 下载文件到本地
 * @author zhoujian
 * @date 2017-6-19
 * @version V1.0 
 */
@Service
public class LoadService
{
	
	private Logger logger = Logger.getLogger(this.getClass());
	/**
	 * 
	 * @Description: 文件下载到本地目录
	 * @return void
	 * @throws
	 */
	public String loadToLocal(String rootPath, List<Object> grid_forecasts , ServerService serverService)
	{
		try
		{
			//黑龙江项目屏蔽ftp下载数据
			Map<Integer, List<String>> serverIdAndFilePaths = classifyByServer(grid_forecasts);
			for (Map.Entry<Integer, List<String>> entry : serverIdAndFilePaths.entrySet()) {
				int id = entry.getKey();
				List<String> pathList = entry.getValue();
				// 下载
				rootPath = this.load(id, pathList, rootPath , serverService);
			}
		}
		catch (Exception e)
		{
			logger.error("Data file load to local exception , this exception is : " + e);
		}
		return rootPath;
	}
	
	public String load(int id, List<String> pathList, String rootPath ,  ServerService serverService) {
		try {
			Server server = (Server) serverService.getServerById(id);
			String ip = server.getIp();
			String username = server.getUsername();
			String password = server.getPassword();
			// String port = server.getPort();
			//获取本机ip
			if (getHostAddress().contains(ip))
			{
				rootPath = "";
			}else{
				String[] remoteFileNames = new String[pathList.size()];
				pathList.toArray(remoteFileNames);
				FTPClientFactory.loadFile(remoteFileNames, rootPath, ip, username, password);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("FTP load file exception , this exception is : ", e);
		}
		return rootPath;
	}
	
	/**
	 * 
	 * @Description: 通过服务器分类
	 * @return Map<Integer,List<String>>
	 * @throws
	 */
	public Map<Integer, List<String>> classifyByServer(List<Object> grid_forecasts) {
		Map<Integer, List<String>> serverIdAndFilePaths = new HashMap<Integer, List<String>>();
		List<Integer> serverIdList = new ArrayList<Integer>();

		try
		{
			int serverId;
			for (Object object : grid_forecasts) {
				GridForecast gf = (GridForecast) object;
				serverId = gf.getServer_id();
				if (!serverIdList.contains(serverId)) {
					serverIdList.add(serverId);
				}
			}
			String filePath;
			for (Integer id : serverIdList) {
				List<String> pathList = new ArrayList<String>();
				for (Object object : grid_forecasts) {
					GridForecast gf = (GridForecast) object;
					if (id == gf.getServer_id()) {
						filePath = gf.getForecast_filepath();
						pathList.add(filePath);
					}
				}
				serverIdAndFilePaths.put(id, pathList);
			}
		}
		catch (Exception e)
		{
			logger.error("Sorting exceptions by server , this exception is : " + e);
		}
		return serverIdAndFilePaths;
	}
	
	private List<String> getHostAddress() throws Exception
	{
		List<String> hostIps = new ArrayList<String>(5);
		if (System.getProperty("os.name").toLowerCase().contains("windows"))
		{
			InetAddress ia =  InetAddress.getLocalHost();
			hostIps.add(ia.getHostAddress());
		}
		else {
			hostIps = getLinuxHostAddress();
		}
		return hostIps;
	}

	/**
	 * 
	 * @Description: 获取Linux服务器的IP地址
	 * @return List<String>
	 * @throws
	 */
	private List<String> getLinuxHostAddress() throws Exception
	{
		List<String> hostAddres = new ArrayList<String>();
		InetAddress ip = null; //声明一个InetAddress类型ip地址  
		 Enumeration<NetworkInterface> allNetInterfaces;  //定义网络接口枚举类  
        allNetInterfaces = NetworkInterface.getNetworkInterfaces();  //获得网络接口  
  
        while (allNetInterfaces.hasMoreElements()) //遍历所有的网络接口  
        {  
            NetworkInterface netInterface = allNetInterfaces.nextElement();  
//            System.out.println(netInterface.getName());  //打印网端名字  
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); //同样再定义网络地址枚举类  
            while (addresses.hasMoreElements())  
            {  
                ip = addresses.nextElement();  
                if (ip != null && (ip instanceof Inet4Address)) //InetAddress类包括Inet4Address和Inet6Address  
                {  
                	hostAddres.add(ip.getHostAddress());
//                    System.out.println("本机的IP = " + ip.getHostAddress());  
                }   
            }  
        }  
        return hostAddres;
	}
}
